package pl.lodz.p.pai.storehouse.db;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import pl.lodz.p.pai.storehouse.types.Storehouse;

public class IbatisStorehouseDao implements StorehouseDao {

	private static int[] mutex= new int[0];
	private boolean initialized=false;

	private SqlSessionFactory sqlSessionFactory;
	
	private  SqlSessionFactory getSqlSessionFactory() {
		if(sqlSessionFactory==null){
			synchronized(mutex){
				if(!initialized){
					DataSource dataSource = locateDataSource();
					TransactionFactory transactionFactory = new JdbcTransactionFactory();
					Environment environment = new Environment("development", transactionFactory, dataSource);
					Configuration configuration = new Configuration(environment);
					configuration.addMapper(StorehouseMapper.class);
					sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
					initialized=true;
				}
			}
		}
		return sqlSessionFactory;
		

	}

	private DataSource locateDataSource() {
		
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/storehouseDS");
			return ds;
		} catch (NamingException e) {			
			return null;
		}

	}
	
	public Storehouse getStorehouse(String id) {
		Storehouse result = new Storehouse();
		SqlSession session = getSqlSessionFactory().openSession();
		try {
			StorehouseMapper mapper=session.getMapper(StorehouseMapper.class);
			result = mapper.getStorehouse(id);
			session.commit();
		} finally {
		  session.close();
		}
		return result;
	}
	
}
